import { ElMessage, ElLoading } from 'element-plus'
import errorCode from '@/utils/errorCode'
import service from './axios'
import { saveAs } from "file-saver";
import { blobValidate } from "@/utils/ruoyi";


export function post(url, data) {
  return service({
    method: 'post',
    url,
    data
  })
}


export function submitForm(url, data = {}) {
  service.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  return service({
    method: 'post',
    url,
    data,
    // headers: {
    //   "Content-Type": "multipart/form-data"
    // },
    transformRequest: [ // 回调中接收到请求的数据,转为键值对格式
      (data) => {
        let ret = ""
        for (let it in data) {
          const cur = data[it]
          if(cur==null || cur==='' || cur == undefined || JSON.stringify(cur)==='{}' || JSON.stringify(cur)==='[]'){
            continue
          }
          ret +=
            encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&"
        }
        return ret
      }
    ]
  })
}


/**
 * 通用下载方法
 * @param {*} url 请求地址
 * @param {*} params 请求参数
 * @param {*} config 配置
 * @returns
 */

let downloadLoadingInstance
export async function downFile(url, params, config) {
  downloadLoadingInstance = ElLoading.service({
    text: '正在下载数据，请稍候',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  service
    .get(url, {
      params,
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
      ...config
    })
    .then(async (resp) => {
      const { data } = resp

      const isLogin = await blobValidate(data)
      if (isLogin) {
        var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
        var contentDisposition = decodeURI(resp.headers['content-disposition'])
        var result = patt.exec(contentDisposition)
        var fileName = result[1]
        fileName = fileName.replace(/\"/g, '')

        const blob = new Blob([data])
        // saveAs(blob, fileName)
      } else {
        const resText = await data.text()
        const rspObj = JSON.parse(resText)
        const errMsg =
          errorCode[rspObj.code] || rspObj.msg || errorCode['default']

        ElMessage({
          message: errMsg,
          type: 'error'
        })
      }
      downloadLoadingInstance.close()
    })
    .catch((err) => {
      ElMessage({
        message: '下载文件出现错误，请联系管理员！',
        type: 'error'
      })
      downloadLoadingInstance.close()
    })
}
